#!/bin/bash

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

LOG_FILE="${CONFIG_HOME}/logs/system_apps_$(date +%Y%m%d).log"

# 确保日志目录存在
mkdir -p "${CONFIG_HOME}/logs"

log() {
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] $1" >> "$LOG_FILE"
}

log "开始处理系统应用"

# 系统应用列表
SYSTEM_APPS=(
    "App Store.app"
    "Automator.app"
    "Calculator.app"
    "Calendar.app"
    "Chess.app"
    "Contacts.app"
    "Dictionary.app"
    "FaceTime.app"
    "Home.app"
    "Image Capture.app"
    "Launchpad.app"
    "Mail.app"
    "Maps.app"
    "Messages.app"
    "Mission Control.app"
    "Music.app"
    "News.app"
    "Notes.app"
    "Photo Booth.app"
    "Photos.app"
    "Podcasts.app"
    "Preview.app"
    "QuickTime Player.app"
    "Reminders.app"
    "Safari.app"
    "Stickies.app"
    "Stocks.app"
    "System Information.app"
    "System Preferences.app"
    "TextEdit.app"
    "Time Machine.app"
    "TV.app"
    "Utilities"
    "Voice Memos.app"
    "Weather.app"
)

# 从备份恢复系统应用到原始目录
for app in "${SYSTEM_APPS[@]}"; do
    if [ -e "${CONFIG_HOME}/backup/MacOS12SystemApps/$app" ] && [ ! -e "/Applications.original/$app" ]; then
        log "恢复系统应用到原始目录: $app"
        sudo cp -R "${CONFIG_HOME}/backup/MacOS12SystemApps/$app" "/Applications.original/"
    fi
done

# 创建系统应用覆盖链接
for app in "${SYSTEM_APPS[@]}"; do
    if [ -e "/Applications.original/$app" ]; then
        if [ -e "/Applications/$app" ] && [ ! -L "/Applications/$app" ]; then
            log "替换标准应用为链接: $app"
            sudo rm -rf "/Applications/$app.temp" 2>/dev/null
            sudo mv "/Applications/$app" "/Applications/$app.temp" 2>/dev/null
            sudo ln -sf "/Applications.original/$app" "/Applications/$app"
            sudo rm -rf "/Applications/$app.temp" 2>/dev/null
        elif [ ! -e "/Applications/$app" ]; then
            log "创建系统应用链接: $app"
            sudo ln -sf "/Applications.original/$app" "/Applications/$app"
        fi
    fi
done

log "系统应用处理完成"
